package com.shine.chemicalWholeProcessSystem.ui.riskManagement;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.shine.chemicalWholeProcessSystem.BR;
import com.shine.chemicalWholeProcessSystem.R;
import com.shine.chemicalWholeProcessSystem.app.Constants;
import com.shine.chemicalWholeProcessSystem.base.BaseActivity;
import com.shine.chemicalWholeProcessSystem.bean.DictionariesBean;
import com.shine.chemicalWholeProcessSystem.bean.RiskManagementBean;
import com.shine.chemicalWholeProcessSystem.bean.RiskManagementCreateBean;
import com.shine.chemicalWholeProcessSystem.databinding.ActivityRiskManagementCreateBinding;
import com.shine.chemicalWholeProcessSystem.http.ApiException;
import com.shine.chemicalWholeProcessSystem.http.BaseReturn;
import com.shine.chemicalWholeProcessSystem.http.ECHttpResponse;
import com.shine.chemicalWholeProcessSystem.http.ECObserver;
import com.shine.chemicalWholeProcessSystem.http.RetrofitClient;
import com.shine.chemicalWholeProcessSystem.http.RxUtils;
import com.shine.chemicalWholeProcessSystem.http.Service;
import com.shine.chemicalWholeProcessSystem.utils.SPUtils;

import java.util.ArrayList;
import java.util.List;

public class RiskManagementCreateActivity extends BaseActivity<ActivityRiskManagementCreateBinding, RiskManagementCreateViewModel> {
    private boolean isEdit;
    private String id;
    private List<String> dataStrList = new ArrayList<>();
    private RiskManagementCreateBean bean = new RiskManagementCreateBean();

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_risk_management_create;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public RiskManagementCreateViewModel initViewModel() {
        return new RiskManagementCreateViewModel(this);
    }

    @Override
    public int appTheme() {
        return Constants.THEME_FULL;
    }

    @Override
    public void initData() {
        super.initData();
        setStatusBar();
        initTitle(this, "风险点管理");

        isEdit = getIntent().getBooleanExtra(Constants.BUNDLE_EDIT, false);

        if (isEdit) {
            showView((RiskManagementBean) getIntent().getSerializableExtra(Constants.BUNDLE_EXTRA));
            binding.secondTitle.setText("编辑风险点");
            binding.add.setText("确  认  编  辑");
        } else {
            binding.secondTitle.setText("添加风险点");
            binding.add.setText("确  认  添  加");
        }
        binding.riskClassification.setOnClickListener(this);
        binding.isMajorHazard.setOnClickListener(this);
        binding.riskClassificationMethod.setOnClickListener(this);
        binding.exposureFrequency.setOnClickListener(this);
        binding.severity.setOnClickListener(this);
        binding.riskLevel.setOnClickListener(this);
        binding.industryCategory.setOnClickListener(this);
        binding.accidentProneTypes.setOnClickListener(this);
        binding.occupationalHazardFactors.setOnClickListener(this);
        binding.add.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.riskClassification:
                getDictionaries(0);
//                showBottomPop(0, ChooseData.riskClassificationList());
                break;
            case R.id.isMajorHazard:
                getDictionaries(1);
//                showBottomPop(1, ChooseData.yesOrNo());
                break;
            case R.id.riskClassificationMethod:
                getDictionaries(8);
//                showBottomPop(1, ChooseData.yesOrNo());
                break;
            case R.id.exposureFrequency:
                getDictionaries(2);
//                showBottomPop(2, ChooseData.nothing());
                break;
            case R.id.severity:
                getDictionaries(3);
//                showBottomPop(3, ChooseData.severityList());
                break;
            case R.id.riskLevel:
                getDictionaries(4);
//                showBottomPop(4, ChooseData.riskLevelList());
                break;
            case R.id.industryCategory:
                getDictionaries(5);
//                showBottomPop(5, ChooseData.industryCategoryList());
                break;
            case R.id.accidentProneTypes:
                getDictionaries(6);
//                showBottomPop(6, ChooseData.accidentProneTypesList());
                break;
            case R.id.occupationalHazardFactors:
                getDictionaries(7);
//                showBottomPop(7, ChooseData.occupationalHazardFactorsList());
                break;
            case R.id.add:
                PostSaveDangerousPoint();
                break;
            default:
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                default:
                    break;
            }
        }
    }

    private void showView(RiskManagementBean bean) {
        id = bean.getId();
        binding.companyName.setText(bean.getLeader());
        binding.phone.setText(bean.getContactnum());
        binding.riskName.setText(bean.getPointname());
        binding.number.setText(bean.getPointcode());
        //binding.riskClassification.setText(bean.getRiskclass());
        //binding.isMajorHazard.setText(bean.getIsMajorHazard());
        //binding.riskClassificationMethod.setText(bean.getClassmethod());
        binding.possibility.setText(bean.getPossibility());
        //binding.exposureFrequency.setText(bean.getExposureFrequency());
        //binding.severity.setText(bean.getSeverity());
        //binding.riskLevel.setText(bean.getRiskLevel());
        binding.siteName.setText(bean.getSitename());
        binding.industry.setText(bean.getIndustry());
        //binding.industryCategory.setText(bean.getIndustrycategory());
        binding.position.setText(bean.getPosition());
        //binding.accidentProneTypes.setText(bean.getAccidentpronetype());
        //binding.occupationalHazardFactors.setText(bean.getOccupationalhazardscategory());
        binding.occupationalHazardFactorsEdit.setText(bean.getOccupationalhazardsname());
        binding.mainHazardHarmfulness.setText(bean.getMaindangerharmfulness());
        binding.controlMeasures.setText(bean.getControlmeasures());
    }

    private void PostSaveDangerousPoint() {
        showLoading("");

        if (isEdit)
            bean.setId(id);
        else
            bean.setId("");
        bean.setLeader(binding.companyName.getText().toString());
        bean.setContactNum(binding.phone.getText().toString());
        bean.setPointName(binding.riskName.getText().toString());
        bean.setPointCode(binding.number.getText().toString());
//        bean.setRiskClass("");//bean.setRiskClass(binding.riskClassification.getText().toString());
//        bean.setIsMajorHazard("");//bean.setIsMajorHazard(binding.isMajorHazard.getText().toString());
//        bean.setClassMethod("");//bean.setClassMethod();
        bean.setPossibility(binding.possibility.getText().toString());
//        bean.setExposureFrequency("");//bean.setExposureFrequency(binding.exposureFrequency.getText().toString());
//        bean.setSeverity("");//bean.setSeverity(binding.severity.getText().toString());
//        bean.setRiskLevel("");//bean.setRiskLevel(binding.riskLevel.getText().toString());
        bean.setSiteName(binding.siteName.getText().toString());
        bean.setIndustry(binding.industry.getText().toString());
//        bean.setIndustryCategory("");//bean.setIndustryCategory(binding.industryCategory.getText().toString());
        bean.setPosition(binding.position.getText().toString());
//        bean.setAccidentProneType("");//bean.setAccidentProneType(binding.accidentProneTypes.getText().toString());
//        bean.setOccupationalHazardsCategory("");//bean.setOccupationalHazardsCategory(binding.occupationalHazardFactors.getText().toString());
        bean.setOccupationalHazardsName(binding.occupationalHazardFactorsEdit.getText().toString());
        bean.setMainDangerHarmfulness(binding.mainHazardHarmfulness.getText().toString());
        bean.setControlMeasures(binding.controlMeasures.getText().toString());

        RetrofitClient.getInstance().create(Service.class)
                .PostSaveDangerousPoint(new Gson().toJson(bean))
                .compose(RxUtils.<ECHttpResponse<BaseReturn>>bindToLifecycle(this))
                .compose(RxUtils.<ECHttpResponse<BaseReturn>>schedulersTransformer())
                .compose(RxUtils.<ECHttpResponse<BaseReturn>>exceptionTransformer())
                .subscribe(new ECObserver<BaseReturn>() {
                    @Override
                    protected void _onNext(BaseReturn baseReturn) {
                        dismissLoading();
                        if (isEdit)
                            ToastMessage("编辑成功");
                        else
                            ToastMessage("新增成功");
                        finishActivityForResult();
                    }

                    @Override
                    protected void _onError(ApiException ex) {
                        ToastMessage(ex.message);
                        dismissLoading();
                    }
                });
    }

    private void getDictionaries(int type) {
        //风险分类(RiskClass)
        String typeStr = "";
        switch (type) {
            case 0:
                typeStr = "RiskClass";
                break;
            case 1:
                typeStr = "YesOrNo";
                break;
            case 2:
                typeStr = "ExposureFrequency";
                break;
            case 3:
                typeStr = "Severity";
                break;
            case 4:
                typeStr = "wxdj";
                break;
            case 5:
                typeStr = "IndustryCategory";
                break;
            case 6:
                typeStr = "sglx";
                break;
            case 7:
                typeStr = "zybwxys";
                break;
            case 8:
                typeStr = "ClassMethod";
                break;
            default:
                break;
        }


        showLoading("");
        RetrofitClient.getInstance().create(Service.class)
                .details(typeStr, SPUtils.getInstance().getString(Constants.SP_TOKEN), SPUtils.getInstance().getString(Constants.SP_MARK))
                .compose(RxUtils.<ECHttpResponse<List<DictionariesBean>>>bindToLifecycle(this))
                .compose(RxUtils.<ECHttpResponse<List<DictionariesBean>>>schedulersTransformer())
                .compose(RxUtils.<ECHttpResponse<List<DictionariesBean>>>exceptionTransformer())
                .subscribe(new ECObserver<List<DictionariesBean>>() {
                    @Override
                    protected void _onNext(List<DictionariesBean> dictionariesBeanList) {
                        dismissLoading();
                        dataStrList.clear();
                        for (DictionariesBean dictionariesBean : dictionariesBeanList) {
                            dataStrList.add(dictionariesBean.getF_ItemName());
                        }
                        showBottomPop(type, dataStrList, dictionariesBeanList);
                    }

                    @Override
                    protected void _onError(ApiException ex) {
                        ToastMessage(ex.message);
                        dismissLoading();
                    }
                });
    }


    private String[] data = null;

    private void showBottomPop(int type, List<String> dataList, List<DictionariesBean> dictionariesBeanList) {
        data = dataList.toArray(new String[0]);

        new XPopup.Builder(RiskManagementCreateActivity.this)
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                .maxHeight(1000)
                .asBottomList("请选择一项", data,
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int positionInt, String text) {
                                switch (type) {
                                    case 0:
                                        binding.riskClassification.setText(data[positionInt]);
                                        bean.setRiskClass(dictionariesBeanList.get(positionInt).getF_ItemValue());
                                        break;
                                    case 1:
                                        binding.isMajorHazard.setText(data[positionInt]);
                                        bean.setIsMajorHazard(dictionariesBeanList.get(positionInt).getF_ItemValue());
                                        break;
                                    case 8:
                                        binding.riskClassificationMethod.setText(data[positionInt]);
                                        bean.setClassMethod(dictionariesBeanList.get(positionInt).getF_ItemValue());
                                        break;
                                    case 2:
                                        binding.exposureFrequency.setText(data[positionInt]);
                                        bean.setExposureFrequency(dictionariesBeanList.get(positionInt).getF_ItemValue());
                                        break;
                                    case 3:
                                        binding.severity.setText(data[positionInt]);
                                        bean.setSeverity(dictionariesBeanList.get(positionInt).getF_ItemValue());
                                        break;
                                    case 4:
                                        binding.riskLevel.setText(data[positionInt]);
                                        bean.setRiskLevel(dictionariesBeanList.get(positionInt).getF_ItemValue());
                                        break;
                                    case 5:
                                        binding.industryCategory.setText(data[positionInt]);
                                        bean.setIndustryCategory(dictionariesBeanList.get(positionInt).getF_ItemValue());
                                        break;
                                    case 6:
                                        binding.accidentProneTypes.setText(data[positionInt]);
                                        bean.setAccidentProneType(dictionariesBeanList.get(positionInt).getF_ItemValue());
                                        break;
                                    case 7:
                                        binding.occupationalHazardFactors.setText(data[positionInt]);
                                        bean.setOccupationalHazardsCategory(dictionariesBeanList.get(positionInt).getF_ItemValue());
                                        break;
                                    default:
                                        break;
                                }
                            }
                        })
                .show();
    }
}
